import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore, useBreadcrumbStore } from '@/store';
import { progress, getBreadcrumb } from './routeTools';
import routes from './routes';

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

/** 全局前置路由守卫 */
router.beforeEach((to, from) => {
  progress.start();

  // 动态设置标题
  const title = import.meta.env.VITE_APP_TITLE;
  document.title = to.meta.title ? `${window.$t(to.meta.title)} - ${title}` : title;

  if (localStorage.getItem('userInfo')) {
    const redirectUrl = from.fullPath.split('redirect=')?.[1];
    if (redirectUrl && to.fullPath !== redirectUrl) return redirectUrl;

    const { roles } = to.meta;
    //若前往的路由有权限设置
    if (roles && Array.isArray(roles)) {
      const { userInfo } = useUserStore();
      if (!roles.includes(userInfo.role)) {
        window.$message.warning('您暂无进入此页面的权限');
        return false;
      }
    }
    // 路由跳转时确定当前面包屑
    const breadcrumbStore = useBreadcrumbStore();
    breadcrumbStore.breadcrumb = getBreadcrumb(to);
  } else {
    //未登录，需要判断是否正处于登录页，否则会无限循环
    if (from.path !== '/login' && to.path === '/login') {
      //处于登录页则放行
      return;
    } else {
      //否则跳转登录页
      window.$message.warning('请登录');
      return `/login?redirect=${to.fullPath}`;
    }
  }
});
/** 路由跳转结束 */
router.afterEach(() => {
  progress.done();
});

export default router;
